const baseUrl = 'http://localhost:8080';
const userUrl = baseUrl + '/user';

function login(username, password) {
    fetch(userUrl + "/up", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            username: username,
            password: password,
        })
    }).then(response => {
        if (response.ok) {
            return response.json();
        }
        throw new Error(response.statusText);
    }).then(result => {
        if(result.ok) {
            return result.data;
        }
        throw new Error(result.msg);
    }).then(user => {
        sessionStorage.setItem('user', JSON.stringify(user));
        console.log("登录成功");
        alert(`欢迎用户${user.nickname}`);
        location.href = "main.html"

        return true;
    }).catch(error => {
        alert("用户名或密码错误");
        console.log(error);
    })
    return false;
}

function register(nickname, username, password) {
    fetch(userUrl + "/reg", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            username: username,
            password: password,
            nickname: nickname,
        })
    }).then(response => {
        if (response.ok) {
            return response.json();
        }
        throw new Error(response.statusText);
    }).then(result => {
        if(result.ok) {
            return result.data;
        }
        throw new Error(result.msg);
    }).then(user => {
        sessionStorage.setItem('user', JSON.stringify(user));
        console.log("注册成功");
        location.href = "main.html"

        return true;
    }).catch(error => {
        alert("用户名已存在");
        console.log(error);
    })
    return false;
}
